let color = "{COOKIE_color}";
$(function () {
   $.post("./?/getRoomList",{},function (text) {
      let data = JSON.parse(text);
      console.log(data);
      let content = "";
      $.post("./?/getHost",{},function (text) {
         let host = text;
         $.post("./?/isAdmin",{},function (text) {
            let isSAdmin = text === "yes";
            let roomCount = 0;
            for (const dataKey in data) {
               let room = data[dataKey];
               let roomId = dataKey;
               let canSendPic = room.sendPic === "yes";
               let sendPicFlag = canSendPic ? `<p><span class="fa fa-check text-green"></span> 可以发送图片` : `<p><span class="fa fa-close text-red"></span> 不可发送图片`;
               let hasPassword = room.enablePassword === "yes" ? ` <span class="fa fa-lock text-red"></span> 有密码</p>`:`</p>`;
               let admin = room.admin;
               let isAdmin = admin.toString() === host || isSAdmin;
               let deleteFlag = isAdmin ? `<li><a class="btn btn-flat waves-button waves-effect waves-light" onclick="deleteRoom(\'${roomId}\')"><span class="icon">delete</span><span class="text">删除</span></a></li>`:``;
               let a = `<div class="col-lg-3 col-md-4 col-sm-6"><div class="card"><div class="card-main"><div class="card-inner"><p class="card-heading">房间号：${roomId}</p><p>管理员编号：${admin}</p>${sendPicFlag} ${hasPassword}</div><div class="card-action"><ul class="nav nav-list pull-left"><li><a class="btn btn-flat waves-button waves-effect waves-light" onclick="gotoRoom(\'${roomId}\')"><span class="icon">add</span><span class="text">前往</span></a></li>${deleteFlag}</ul></div></div></div></div>`;
               content += a;
               roomCount++;
            }
            $("#roomCount").text(roomCount);
            if (content.length>0) {
               $("#list-main-div").html(content);
            }
            loadColor();
         });
      })
   });
   $("#deleteBtn").click(function () {
      let id = $("#deleteRoomId").text();
      $.post("./?/deleteRoom",{
         id:id
      },function (text) {
         location.reload();
      })
   });
});
function deleteRoom(id) {
   $("#deleteRoomId").text(id);
   $("#open-modal-delete").click();
}
function gotoRoom(id) {
   $.post("./?/joinChat",{
      roomId:id
   },function (text) {
      if (text.indexOf("password")!==-1){
         let p = prompt("请输入房间密码");
         if (p !== null){
            $.cookie("roomPassword",p);
            location.href="./?/main";
         }
      }else if (text==="success") {
         window.open("./?/main", "_self");
      }
   })
}